package com.gla.market.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.R;
import com.gla.market.SearchHistoryDatabase.PetShopDatabaseHelper;
import com.gla.market.adapter.FYH_EvaluationAdapter;
import com.gla.market.adapter.FYH_VedioAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Commodity;
import com.gla.market.entity.FYH_Evaluation;
import com.gla.market.entity.FYH_ShopCar;
import com.gla.market.entity.FYH_Vedio;
import com.gla.market.entity.ShopCart;
import com.gla.market.entity.ShopInCart;
import com.gla.market.fragments.Shopcart;
import com.gla.market.utils.NetUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Commodity_FYHActivity extends AppCompatActivity {
    private boolean iseva, canclick;
    private int isvip, cmnum;

    private String cmid;
    private Integer user_id;

    private Commodity thiscm;
    private FYH_ShopCar thiscar;

    private TextView tvback, tvname, tvintro, tvdetail, tvnum, tvprice, eovtv, numtv;
    private ImageView imphoto;

    //定义一个自己的context
    private Context mContext;

    private List<FYH_Evaluation> listEva = new ArrayList<>();
    private FYH_EvaluationAdapter fea;

    private List<FYH_Vedio> listvdo = new ArrayList<>();
    private FYH_VedioAdapter fev;

    private Button buynow, addcar, jianbt, jiabt, logbt;

    private LinearLayout downbtly;

    //推荐产品
    private GridView recommendProductGridView;

    //热评和推荐商品的两个进度条
    private ProgressBar recommendProgressBar;

    //下拉刷新的layout
    private SwipeRefreshLayout mRefreshLayout;

    //本地数据库连接
    private PetShopDatabaseHelper petShopDatabaseHelper;

    //商店信息
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    if(thiscm.getP_o_u() == 0) iseva = false;
                    else iseva = true;
                    String name = thiscm.getName();
                    if(name.length() > 10) name = name.substring(0, 10) + "...";
                    tvname.setText(name);
                    tvprice.setText("￥" + thiscm.getPriceShow());
                    tvintro.setText(thiscm.getIntroduction());
                    tvdetail.setText(thiscm.getDetails());
                    if(thiscm.getP_o_u() != 0) tvnum.setText("剩余库存：" + thiscm.getNumber() + "");
                    else tvnum.setVisibility(View.GONE);
                    if(!"".equals(thiscm.getPhoto())) {
                        ImageLoader.getInstance().displayImage(thiscm.getPhoto(), imphoto);
                    }else{
                        imphoto.setImageResource(R.drawable.fyh_goods_mr);
                    }
                    if(iseva) GetEvaluation();
                    else GetVedio();
                    GetOneCar();

                    /***
                     * 增加前端数据库，获取类别用于推荐算法
                     * **/
                    petShopDatabaseHelper = new PetShopDatabaseHelper(mContext);
                    String userId = user_id.toString();
                    Boolean bool = petShopDatabaseHelper.searchType(thiscm.getType().getName(),userId);
                    if(bool==true){
                        //存在+1 修改num
                        petShopDatabaseHelper.updateType(thiscm.getType().getName(),userId);
                    }else{
                        //不存在这个Type 创建
                        petShopDatabaseHelper.insertType(thiscm.getType().getName(),userId);
                    }
                    break;
                case 3:
                    fea = new FYH_EvaluationAdapter(mContext, listEva);
                    //根据数量动态设置高度
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(GridView.LayoutParams.MATCH_PARENT,dip2px(mContext,listEva.size() * 95));
                    recommendProductGridView.setLayoutParams(params);
                    recommendProductGridView.setAdapter(fea);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        }
                    });
                    eovtv.setText("用户评论");
                    //停止显示加载动画，显示商品信息
                    recommendProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    fev = new FYH_VedioAdapter(mContext, listvdo);
                    //根据数量动态设置高度
                    LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(GridView.LayoutParams.MATCH_PARENT,dip2px(mContext,listvdo.size() * 165));
                    recommendProductGridView.setLayoutParams(params2);
                    recommendProductGridView.setAdapter(fev);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tvid = view.findViewById(R.id.vid);
                            Intent intent = new Intent(Commodity_FYHActivity.this, Video_FYHActivity.class);
                            intent.putExtra("id", tvid.getText().toString());
                            startActivity(intent);
                        }
                    });
                    eovtv.setText("宠物视频");
                    recommendProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                    //获取购物车,加入购物车
                case 5:
                    if(thiscar.getId() > 0){
                        addcar.setText("移出购物车");
                        if(thiscm.getP_o_u() == 1) {
                            cmnum = thiscar.getNumber();
                            numtv.setText(cmnum + "");
                            jianbt.setVisibility(View.VISIBLE);
                            jiabt.setVisibility(View.VISIBLE);
                            numtv.setVisibility(View.VISIBLE);
                        }
                    }
                    else{
                        addcar.setText("加入购物车");
                        jianbt.setVisibility(View.GONE);
                        jiabt.setVisibility(View.GONE);
                        numtv.setVisibility(View.GONE);
                    }
                    canclick = true;
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (mRefreshLayout.isRefreshing()) {
                //停止动画
                mRefreshLayout.setRefreshing(false);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_fyhactivity);

        mContext = this;
        canclick = false;
        cmnum = 0;

        Intent intent = getIntent();
        cmid = intent.getStringExtra("id");

        tvback = findViewById(R.id.commodity_back);
        tvname = findViewById(R.id.commodity_name);
        tvintro = findViewById(R.id.commodity_introduction);
        tvdetail = findViewById(R.id.commodity_details);
        tvnum = findViewById(R.id.commodity_number);
        tvprice = findViewById(R.id.commodity_price);
        imphoto = findViewById(R.id.commodity_photo);
        recommendProgressBar = findViewById(R.id.evabar);
        recommendProductGridView = findViewById(R.id.evaluationlist);
        eovtv = findViewById(R.id.eovtv);
        buynow = findViewById(R.id.buynow);
        addcar = findViewById(R.id.addcar);
        jianbt = findViewById(R.id.jianbt);
        jiabt = findViewById(R.id.jiabt);
        numtv = findViewById(R.id.numtv);
        logbt = findViewById(R.id.logbt);
        downbtly = findViewById(R.id.downbtly);

        logbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(canclick) {
                    if (user_id == -1) {
                        Intent intent = new Intent(Commodity_FYHActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(Commodity_FYHActivity.this, UptoVipActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });

        addcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(canclick) {
                    canclick = false;
                    if(thiscar.getId() == 0) AddCar();
                    else DelCar();
                }
            }
        });

        buynow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BuyNow();
            }
        });

        tvname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, thiscm.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        tvback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        jiabt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(canclick) {
                    canclick = false;
                    UpCar(1);
                }
            }
        });

        jianbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(canclick && cmnum - 1 > 0) {
                    canclick = false;
                    UpCar(-1);
                }
            }
        });

        mRefreshLayout = findViewById(R.id.refresh_layout);
        mRefreshLayout.setOnRefreshListener(mRefreshListener);
    }

    @Override
    protected void onStart() {
        super.onStart();
        GetCommodityMessage();
        usermsg();
    }

    //获取用户信息
    public void usermsg(){
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE); //私有数据
        //获取SharedPreferences编辑器
        user_id = sharedPreferences.getInt("user_id", -1);
        isvip = sharedPreferences.getInt("is_vip", 0);

        if(user_id != -1 && isvip != 0){
            logbt.setVisibility(View.GONE);
            downbtly.setVisibility(View.VISIBLE);
        }
        else{
            downbtly.setVisibility(View.GONE);
            logbt.setVisibility(View.VISIBLE);
        }

        if(isvip == 0) logbt.setText("成为会员");
        if(user_id == -1) logbt.setText("去登录");
    }

    //删除购物车
    public void DelCar(){
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_DELONECAR_URL + thiscar.getId();
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                            JSONObject jshop = object.getJSONObject("data");
                            //获得商品list
                            thiscar = JSONObject.parseObject(String.valueOf(jshop), FYH_ShopCar.class);
                            message.what = 5;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //修改购物车
    public void UpCar(int x){
        if(cmnum + x > 0) {
            String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_UPONECAR_URL + Constants.onecarid(thiscar.getId(), cmnum + x);
            NetUtil.doGet(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("调试", "错误信息：" + e.toString());
                            Message message = Message.obtain();
                            message.what = -1;
                            uiHandler.sendMessage(message);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string().trim();
                            com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                            Message message = Message.obtain();
                            if (object != null && object.getInteger("code") == 100) {
                                JSONObject jshop = object.getJSONObject("data");
                                //获得商品list
                                thiscar = JSONObject.parseObject(String.valueOf(jshop), FYH_ShopCar.class);
                                message.what = 5;
                            } else {
                                message.what = 0;
                            }
                            uiHandler.sendMessage(message);
                        }
                    }
            );
        }
    }

    //加入购物车
    public void AddCar(){
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_SETONECAR_URL + Constants.onecar(thiscm.getId(), user_id);
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                            JSONObject jshop = object.getJSONObject("data");
                            //获得商品list
                            thiscar = JSONObject.parseObject(String.valueOf(jshop), FYH_ShopCar.class);
                            message.what = 5;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //立即购买
    public void BuyNow(){
        ShopCart sc = new ShopCart();
        sc.setCommodity(thiscm);
        if(cmnum == 0) cmnum += 1;
        sc.setNumber(cmnum);
        sc.setUser_id(user_id);
        List<ShopCart> lsc = new ArrayList<>();
        lsc.add(sc);
        ShopInCart sic = new ShopInCart();
        sic.setId(thiscm.getShop().getId());
        sic.setName(thiscm.getShop().getName());
        sic.setList(lsc);
        ArrayList<ShopInCart> list = new ArrayList<>();
        list.add(sic);
        Intent intent = new Intent(mContext, OrderActivity.class);
        //把用户选择的商品传给订单页面
        intent.putExtra("list", list);
        startActivity(intent);
    }

    //刷新
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            if(iseva) GetEvaluation();
            else GetVedio();
        }
    };

    //获取单个购物车
    private void GetOneCar() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_ONECAR_URL + Constants.onecar(thiscm.getId(), user_id);
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                            JSONObject jshop = object.getJSONObject("data");
                            //获得商品list
                            thiscar = JSONObject.parseObject(String.valueOf(jshop), FYH_ShopCar.class);
                            System.out.println(thiscar);
                            message.what = 5;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取视频
    private void GetVedio() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_VEDIOBYCMID_URL + cmid;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            listvdo = JSONArray.parseArray(array.toString(), FYH_Vedio.class);
                            message.what = 4;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取评论
    private void GetEvaluation() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_ALLEVABYCMID_URL + cmid;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            listEva = JSONArray.parseArray(array.toString(), FYH_Evaluation.class);
                            message.what = 3;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取商品
    private void GetCommodityMessage() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_CMBYID_URL + cmid;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                            JSONObject jshop = object.getJSONObject("data");
                            //获得商品list
                            thiscm = JSONObject.parseObject(String.valueOf(jshop), Commodity.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}